﻿<!DOCTYPE html>
<html>

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>获取元素X，Y坐标</title>

		<style type="text/css">
			* {
				margin: 0px;
				padding: 0px;
			}
			
			#box1 {
				border: 5px green solid;
				width: 200px;
				height: 200px;
				margin: 100px;
				position: relative;
			}
			
			#box2 {
				height: 100px;
				width: 100px;
				margin-top: 20px;
				border: 5px blue solid;
				position: absolute;
			}
			
			#box3 {
				height: 50px;
				width: 50px;
				margin-top: 20px;
				border: 5px red solid;
			}
		</style>
	</head>

	<body>
		<div style=" position:absolute; top:20px;">
			<div id="box1">
				<div id="box2">
					<div id="box3"> </div>
				</div>
			</div>
		</div>
		<script>
			window.onload = function() {
				var a = document.getElementById('box3');
				alert(getxy(a));
			}

			function getxy(obj) {
				if(typeof obj == 'object' && obj.nodeType == 1) {
					var x = 0,
						y = 0,
						str;
					while(obj.constructor != HTMLBodyElement) {
						x += obj.offsetLeft + obj.offsetParent.clientLeft;
						y += obj.offsetTop + obj.offsetParent.clientTop;
						obj = obj.offsetParent;
					}
					str = 'x坐标为：' + x + 'y坐标为：' + y;
					return str;
				}
			}
		</script>
	</body>

</html>